Motion Detection

[Computer Vision]

Basic Motion Detection Built From Scratch in Python

Matthew Bird
Tue, Jul 22, 2025

Github Repository: https://github.com/mbird1258/Motion-Detection

Motivation

Current systems for motion activated cameras cost quite a large sum, and thus I thought it would be an interesting project to see how cheap I can get a motion activated camera to be using an ESP32 microcontroller connected to a camera communicating to a central hub. Although I never got around to testing with an ESP32, the code still worked on videos I tested from online.

Method

Similar to my volleyball project here, I take the median of the past n frames to create an estimate of what the background should look like with no moving object in it. Then, I take the difference between the current image and the background, and if the proportion of pixels with a difference above a threshold is above a threshold, motion is detected and a video is saved.

To make the script capable of running in real time with multiple cameras, I also chose to resize the image to 192 x 108 for the median calculations, as that was originally accounting for 95% of the total processing time.

The script saves all the scenes of the input video where movement is detected as a series of videos in an output directory.

Images (taken from the Volleyball project)

Input

Median

Movement Mask

Setup

1. Upload .mp4 files to the In directory 2. Run example.ipynb